#!/bin/sh
#chkconfig:345 80 80
#description: Nginx
#如果需要将此脚本加为服务,则一定要加上面两行
#以下两行命令将nginx脚本加为服务，且在3,4,5级别下自动启动
#     chkconfig --add nginx
#     chkconfig --level 345 nginx on
#注：此脚本一般放在/etc/init.d/目录下


#取用户的uid(保证只有uid为0时才执行)

uid=`id | cut -d ' ' -f1 |sed -e 's/uid=//' -e 's/(.*)//'`
if [ $uid != 0 ]
then

 echo "Fail, Permission denied"

 exit 1
fi



nginx_path="/usr/local/nginx"

pid="$nginx_path/logs/nginx.pid"

nginx="$nginx_path/sbin/nginx"



stage()
{

        echo "Usage nginx {start|stop|status|restart|reload|test}"

        return 0
}



start()
{

        if [ -e "$pid" -a -r "$pid" ]

        then

                echo "Nginx alreay run"

                return 1

        else

                $nginx

                sleep 2

                 if [ -e "$pid" -a -r "$pid" ]

                 then

                        echo "Nginx start OK!"

                        return 0

                 else

                        echo "Nginx start fail"

                        return 1

                 fi

        fi

        return 1
}



stop()
{

        if [ -e "$pid" -a -r "$pid" ]

        then

                $nginx -s stop

                sleep 2

                echo "Nginx is stop"

                return 0

        else

                echo "Nginx is not run"

                return 1

        fi
}



restart()
{

        stop

        if [ $? -eq 0 ]

        then

                start

        fi
}



status()
{

        if [ -e "$pid" -a -r "$pid" ]

        then

                echo Nginx is run, pid=`cat $pid`

        else

                echo Nginx is not run

        fi
}



reload()
{

        if [ -e "$pid" -a -r "$pid" ]

        then

                `$nginx -s reload`

        fi
}



test_config()
{

        if [ -e "$pid" -a -r "$pid" ]

        then

                `$nginx -t 1>&2`

        fi
}


if [ $# != 1 ]
then 

        stage 
else

        case $1 in

                "start") start 

                ;;

                "stop")  stop

                ;;

                "restart") restart

                ;;

                "status") status 

                ;;

                "test") test_config

                ;;

                *) stage 

                ;;

        esac
fi
